<template>
  <el-dialog
    ref="dia"
    :visible.sync="dialogVisible"
    :show="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="750px"
    class="dialog"
    height="480px"
    @close="close"
  >
    <template slot="title">
      <span>
        <span>{{ title }}</span>
<!--        <button class="el-dialog__headerbtn" style="right:50px" @click="minimize">-->
<!--          <el-tooltip content="最小化" effect="dark" placement="left">-->
<!--            <i class="el-icon-minus" style="font-size:14px" />-->
<!--          </el-tooltip>-->
<!--        </button>-->
      </span>
    </template>
    <template v-if="task">
      <div v-for="(item, index) in task.originalData" :key="index">
        <p>{{ item.name }}数：{{ item.data.length }}</p>
        <p>完成{{ item.name }}数：<span style="color:#67C23A;">{{ task.successList[index].length }}</span></p>
        <!-- TODO 失败次数是否在重试后重置 -->
        <p>失败{{ item.name }}数：<span style="color:#F56C6C;">{{ task.failedListCount(index) }}</span></p>
        <p>进度：{{ task.currentState[index] }}/{{ isRetry ? task.failedListCount(index) : item.data.length }}</p>
        <el-progress :text-inside="true" :stroke-width="20" :percentage="task.progress(index)" />
      </div>
      <template v-if="task.subTask">
        <div v-for="(item, index) in task.subTask.originalData" :key="'sub'+index">
          <p>{{ item.name }}数：{{ item.data.length }}</p>
          <p>完成{{ item.name }}数：<span style="color:#67C23A;">{{ task.subTask.successList[index].length }}</span></p>
          <!-- TODO 失败次数是否在重试后重置 -->
          <p>失败{{ item.name }}数：<span style="color:#F56C6C;">{{ task.subTask.failedListCount(index) }}</span></p>
          <p>进度：{{ task.subTask.currentState[index] }}/{{ isRetry ? task.subTask.failedListCount(index) : item.data.length }}</p>
          <el-progress :text-inside="true" :stroke-width="20" :percentage="task.subTask.progress(index)" />
        </div>
      </template>
      <template v-else-if="doubleProgress">
        <div>
          <p>总数：0</p>
          <p>完成数：<span style="color:#67C23A;">0</span></p>
          <p>失败数：<span style="color:#F56C6C;">0</span></p>
          <p>进度：0/0</p>
          <el-progress :text-inside="true" :stroke-width="20" :percentage="0" />
        </div>
      </template>
    </template>
    <el-tabs v-if="task" v-model="activeName" class="tab">
      <el-tab-pane label="执行详细" name="detail">
        <div ref="myScrollbar" class="form-scrollbar">
          <msg v-for="(item, index) in task.messages" :key="index" :message="item.message" :type="item.type" />
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="columns && columns.length > 0 && task.successList.length > 0" name="success">
        <span slot="label">
          <el-badge :value="task.successList[0].length" :hidden="task.successList[0].length === 0" type="success" class="badge">
            <span>成功</span>
          </el-badge>
        </span>
        <table-list :list="task.successList[0]" :columns="columns" />
      </el-tab-pane>
      <el-tab-pane v-if="columns && columns.length > 0 && task.failedList.length > 0" name="error">
        <span slot="label">
          <el-badge :value="task.failedListCount(0)" :hidden="task.failedListCount(0) === 0" type="danger" class="badge">
            <span>失败</span>
          </el-badge>
        </span>
        <table-list :list="task.failedList[0]" :columns="columns" />

      </el-tab-pane>
    </el-tabs>

    <div slot="footer" class="dialog-footer">
      <el-button :loading="submitState === 1" :disabled="submitState === 1" :type="submitStateText[submitState].type" class="btnSub" @click="submit(submitState === 2)">{{ showSubmitStateText }}</el-button>
      <el-button class="btnExit" @click="completedCancel">{{ showCancelStateText }}</el-button>
    </div>
  </el-dialog>
</template>
<script lang="ts">
import Msg from './msg.vue'
import TableList from './tableList.vue'
import Task, { AllDoneMessage, TaskItem } from './task'
import { TabPane, Dialog, Button, Tabs, Progress, Badge } from 'element-ui'
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
/**
 * @method step()
 *
 * submitState 0=未执行，1=执行中，2=重试，3=全部成功
 */
const submitStateText = [
  { text: '执行', type: 'primary' },
  { text: '执行中', type: 'info' },
  { text: '重试', type: 'warning' },
  { text: '完成', type: 'success' }
]
@Component({
  name: 'ProgressDialog',
  components: {
    Msg,
    TableList,
    ElTabPane: TabPane,
    ElDialog: Dialog,
    ElTabs: Tabs,
    ElButton: Button,
    ElProgress: Progress,
    ElBadge: Badge
  }
})
export default class ProgressDialog extends Vue {
    /**  控制显隐 */
    @Prop({ default: false }) show!: boolean
    @Prop({ default: () => [], required: true }) private items!: TaskItem[]
    @Prop({ default: () => [], required: true }) private columns!: any[]
    @Prop({ default: '此操作不可逆，请谨慎操作' }) private title!:string
    @Prop({ default: undefined }) private completedMessage: AllDoneMessage | string | undefined
    @Prop({ default: false }) private doubleProgress!: boolean
    /** 强制完成，即使有失败项 */
    @Prop({ default: false }) private forceComplete!: boolean
    /** 自动开始,弹窗弹出时开始任务，无需点击开始 */
    @Prop({ default: false }) private autoStart!: boolean
    /** 初始执行按钮label文本 */
    @Prop({ default: '' }) private initSubmitText!:string
    /** 初始取消按钮label文本 */
    @Prop({ default: '' }) private initCancelText!:string
    /** 任务完成时执行按钮label文本 */
    @Prop({ default: '' }) private completedSubmitText!:string
    /** 任务完成时取消按钮label文本 */
    @Prop({ default: '' }) private completedCancelText!:string

      dialogVisible = this.show

      btnDisable = false
      submitState = 0
      submitStateText = submitStateText
      pause = false
      activeName = 'detail'

      /** 执行次数 */
      executeNum = 0
      task: Task | null = null
      isMinimize = false

      get isRetry() {
        return this.executeNum > 1
      }

      get showCancelStateText() {
        if (this.submitState === 0 && this.initCancelText) {
          return this.initCancelText
        }
        if (this.submitState === 3 && this.completedCancelText) {
          return this.completedCancelText
        }
        return '取 消'
      }

      get showSubmitStateText() {
        if (this.submitState === 0 && this.initSubmitText) {
          return this.initSubmitText
        }
        if (this.submitState === 3 && this.completedSubmitText) {
          return this.completedSubmitText
        }
        return this.submitStateText[this.submitState].text
      }

  @Watch('show')
      watchShow(val: boolean) {
        this.dialogVisible = val
      }

  created() {
    this.dialogVisible = false
    this.$nextTick(() => {
      this.open()
      this.dialogVisible = true
    })
  }

  open() {
    this.pause = false
    this.task = new Task(this.items, this.completedMessage)
    this.$nextTick(() => {
      // 自动开始
      if (this.autoStart) {
        this.submit()
      }
    })
  }

  submit(retry = false) {
    if (this.submitState === 1) {
      return false
    } else if (this.submitState === 3) {
      this.closeAction()
      return false
    }
    this.submitState = 1
    if (!this.task) return false

    this.task.invoke(retry, () => {
      this.$forceUpdate()
      this.$emit('execute')
    }).then(() => {
      this.executeNum++
      this.submitState = !this.forceComplete && (() => {
        let num = 0
        if (!this.task) return false
        for (const item of this.task.failedList) {
          num += item.length
        }
        return num > 0
      })()
        ? 2
        : 3
      if (!this.forceComplete && this.submitState === 3) {
        this.$emit('allSuccess', this)
      }
      this.$emit('allCompleted', this)
    })
  }

  closeAction() {
    if (!this.isMinimize) {
      if (this.task) {
        this.task.pause()

        if (this.task.totalSuccessNum > 0 || this.forceComplete) {
          this.$emit('closeAction')
        }
      }
      this.$emit('update:show', false)
    }
  }

  close() {
    this.task && this.task.pause()
    console.log('after', this.$listeners)
    this.$emit('completedCloseCallback')
    this.$emit('update:show', false)
    // this.closeAction()
  }

  minimize() {
    this.dialogVisible = false
    this.isMinimize = true
    this.$emit('minimize', this.isMinimize)
  }

  maximize() {
    this.dialogVisible = true
    this.isMinimize = false
    this.$emit('minimize', this.isMinimize)
  }

  completedCancel() {
    this.task && this.task.pause()
    console.log('after', this.$listeners)
    this.$emit('completedCancelCallback')
    this.$emit('update:show', false)
  }
}

</script>
<style scoped>
.form-scrollbar {
    overflow-y: scroll;
    height: 150px;
    background: #222324;
    padding: 0 20px;
}
.tab {
    margin: 20px 0;
}
.badge {
  line-height: 20px;
}
</style>
